<script setup>
import { ref, onMounted, watch, computed, nextTick } from 'vue'
import { userService } from '../../services/user'
import SearchBar from '../../components/user/SearchBar.vue'
import AdvancedSearchForm from '../../components/user/AdvancedSearchForm.vue'
import DataTable from '../../components/common/DataTable.vue'
import TagGroup from '../../components/common/TagGroup.vue'
import { showSuccess, showWarning, showError } from '../../utils/message'
import RoleAssignDialog from '../../components/user/RoleAssignDialog.vue'
import { useUserStore } from '../../stores/user'
import UserFormDialog from '../../components/user/UserFormDialog.vue'
import UserDetailDialog from '../../components/user/UserDetailDialog.vue'
import { ElMessageBox } from 'element-plus'

// 角色类型映射
const roleTypeMap = {
  'ROLE_SUPER_ADMIN': 'danger',    // 系统管理员 - 红色
  'ROLE_BUSINESS_STAFF': 'primary', // 业务员 - 蓝色
  'ROLE_OPERATOR': 'warning',      // 操作员 - 黄色
  'ROLE_MANAGER': 'success',       // 负责人 - 绿色
  'ROLE_FINANCE': 'info'           // 财务员 - 灰色
}

// 判断是否为admin用户
const isAdminUser = (user) => {
  return user && user.username === 'admin';
}

// 获取角色标签类型
const getRoleType = (roleCode) => {
  return roleTypeMap[roleCode] || 'info'
}

// 表格数据
const tableData = ref([])

// 分页配置
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表格列配置
const columns = [
  { prop: 'username', label: '用户名', width: '120', align: 'center' },
  { prop: 'real_name', label: '姓名', width: '100', align: 'center' },
  { prop: 'email', label: '邮箱', width: '180', align: 'center' },
  { prop: 'phone', label: '手机号', width: '120', align: 'center' },
  { 
    prop: 'roles', 
    label: '角色', 
    width: '100', 
    align: 'center',
    slot: 'roles'
  },
  { 
    prop: 'status', 
    label: '状态', 
    width: '80', 
    align: 'center',
    slot: 'status'
  },
  { 
    prop: 'last_login_time', 
    label: '最后登录时间', 
    width: '180', 
    align: 'center',
    sortable: true
  },
  { 
    prop: 'created_at', 
    label: '创建时间', 
    width: '180', 
    align: 'center',
    sortable: true
  },
  {
    slot: 'actions',
    label: '操作',
    align: 'center',
    fixed: 'right',
  }
]

const loading = ref(false)

// 对话框引用
const roleAssignDialogRef = ref(null)
const userFormDialogRef = ref(null)
const userDetailDialogRef = ref(null)

// 控制高级搜索表单的显示
const showAdvancedSearch = ref(false)

// 当前搜索模式
const searchMode = ref('normal') // 'normal' 或 'advanced'

// 当前搜索参数
const currentSearchParams = ref({})

// 加载用户数据
const loadUsers = async (searchParams = {}) => {
  try {
    loading.value = true
    let response
    
    if (searchMode.value === 'advanced') {
      // 使用高级搜索API
      response = await userService.advancedSearch({
        page: pagination.value.currentPage,
        pageSize: pagination.value.pageSize,
        ...searchParams
      })
    } else {
      // 使用普通搜索API
      response = await userService.getUsers({
        page: pagination.value.currentPage,
        pageSize: pagination.value.pageSize,
        filters: searchParams
      })
    }
    
    // 保存当前的搜索参数
    currentSearchParams.value = searchParams
    
    // 更新表格数据
    tableData.value = response.data
    pagination.value.total = response.total
  } catch (error) {
    showError('加载用户数据失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 监听数据加载完成后恢复选中状态
watch(() => loading.value, async (newVal) => {
  if (!newVal && userStore.selectedUsers.length > 0) {
    await nextTick()
    const storedSelection = userStore.selectedUsers
    // 确保表格组件已经更新
    setTimeout(() => {
      dataTableRef.value?.setSelection(storedSelection)
    }, 0)
  }
})

// 处理普通搜索
const handleSearch = async (params) => {
  searchMode.value = 'normal'
  pagination.value.currentPage = 1
  await loadUsers(params)
}

// 处理高级搜索
const handleAdvancedSearch = async (params) => {
  searchMode.value = 'advanced'
  pagination.value.currentPage = 1
  await loadUsers(params)
  
  // 成功后关闭高级搜索表单
  showAdvancedSearch.value = false
}

// 切换高级搜索表单显示
const toggleAdvancedSearch = () => {
  showAdvancedSearch.value = !showAdvancedSearch.value
}

// 取消高级搜索
const cancelAdvancedSearch = () => {
  showAdvancedSearch.value = false
}

// 处理表格操作
const handleTableAction = async ({ action, row }) => {
  try {
    // 如果是admin用户且操作不是查看，则不允许操作
    if (isAdminUser(row) && action !== 'detail') {
      showWarning('系统管理员(admin)账号不允许被修改');
      return;
    }
    
    switch (action) {
      case 'detail':
        userDetailDialogRef.value?.openDialog(row.id)
        break
      case 'edit':
        userStore.setCurrentUser(row)
        userFormDialogRef.value?.openDialog()
        break
      case 'delete':
        try {
          await ElMessageBox.confirm(
            `确定要删除用户 ${row.real_name}(${row.username}) 吗？`,
            '删除确认',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          )
          try {
            await userService.deleteUsers([row.id])
            showSuccess('删除成功')
            await loadUsers(currentSearchParams.value)
          } catch (error) {
            // 处理删除失败的情况
            if (error.message.includes('未找到') || error.message.includes('不存在')) {
              showWarning('用户可能已被删除或不存在')
            } else {
              showError(error.message || '删除失败')
            }
            // 刷新列表，确保数据一致性
            await loadUsers(currentSearchParams.value)
          }
        } catch (err) {
          if (err !== 'cancel') {
            throw err
          }
        }
        break
      case 'assign':
        userStore.setSelectedUsers([row])
        roleAssignDialogRef.value?.openAssignDialog()
        break
      case 'status':
        const newStatus = row.status === 1 ? 0 : 1
        const action = newStatus === 1 ? '启用' : '禁用'
        try {
          await ElMessageBox.confirm(
            `确定要${action}用户 ${row.real_name}(${row.username}) 吗？`,
            `${action}确认`,
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          )
          await userService.updateStatus([row.id], newStatus)
          showSuccess(`${action}成功`)
          await loadUsers(currentSearchParams.value)
        } catch (err) {
          if (err !== 'cancel') {
            throw err
          }
        }
        break
    }
  } catch (error) {
    showError('操作失败')
    console.error(error)
  }
}

// 选中的行数据
const dataTableRef = ref(null)
const selection = ref([])

const userStore = useUserStore()

// 修改为使用一个独立的状态来存储当前选中的用户
const selectedUsers = ref([])

// 修改选择处理逻辑
const handleSelectionChange = (selected) => {
  // 同时更新本地状态和 store 状态
  nextTick(() => {
    selectedUsers.value = [...selected]
    userStore.setSelectedUsers(selected)
  })
}

// 修改批量操作方法
const handleBatchAction = async (action) => {
  if (action === 'add') {
    userFormDialogRef.value?.openDialog()
    return
  }
  
  if (action !== 'export' && !selectedUsers.value.length) {
    showWarning('请选择要操作的用户')
    return
  }

  // 检查是否选中了admin用户
  const hasAdminUser = selectedUsers.value.some(user => isAdminUser(user));
  
  try {
    // 如果选中了admin用户且不是导出操作，提示不允许操作
    if (hasAdminUser && action !== 'export') {
      showWarning('选中的用户中包含系统管理员(admin)账号，不允许进行批量操作');
      return;
    }
    
    switch (action) {
      case 'assign':
        roleAssignDialogRef.value?.openAssignDialog()
        break
      case 'delete':
        try {
          await ElMessageBox.confirm(
            `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？`,
            '删除确认',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          )
          try {
            const userIdsToDelete = selectedUsers.value.map(item => item.id)
            await userService.deleteUsers(userIdsToDelete)
            showSuccess('批量删除成功')
            // 清空选择状态
            selectedUsers.value = []
            userStore.clearSelection()
            await loadUsers(currentSearchParams.value)
          } catch (error) {
            // 处理批量删除失败的特定情况
            showError(error.message || '批量删除失败')
            // 刷新列表以确保数据一致性
            await loadUsers(currentSearchParams.value)
            // 由于列表已刷新，清空选择状态
            selectedUsers.value = []
            userStore.clearSelection()
          }
        } catch (err) {
          if (err !== 'cancel') {
            throw err
          }
        }
        break
      case 'export':
        await userService.exportUsers()
        showSuccess('导出成功')
        break
      case 'enable':
        await userService.updateStatus(selectedUsers.value.map(item => item.id), 1)
        showSuccess('批量启用成功')
        await loadUsers(currentSearchParams.value)
        break
      case 'disable':
        await userService.updateStatus(selectedUsers.value.map(item => item.id), 0)
        showSuccess('批量禁用成功')
        await loadUsers(currentSearchParams.value)
        break
    }
  } catch (error) {
    showError('操作失败')
    console.error(error)
  }
}

// 处理角色分配确认
const handleRoleAssignConfirm = async (roleIds, filteredUsers) => {
  if (!roleIds.length) {
    showWarning('请选择至少一个角色')
    return
  }

  try {
    // 使用过滤后的用户列表（已排除admin）
    const selectedIds = filteredUsers.map(item => item.id)
    
    // 显示loading消息
    loading.value = true
    
    // 调用分配角色API
    const results = await userService.assignRoles(selectedIds, roleIds)
    
    // 获取成功结果的第一个消息，如果API返回
    const firstSuccessMessage = results.length > 0 && results[0].message ? results[0].message : null
    
    // 根据分配结果显示消息
    if (selectedIds.length === 1) {
      // 单个用户分配
      const userName = filteredUsers[0].real_name || filteredUsers[0].username
      showSuccess(firstSuccessMessage || `成功为用户 ${userName} 分配角色`)
    } else {
      // 批量分配
      showSuccess(`成功为 ${results.length} 个用户分配角色`)
    }
    
    // 清空选择状态
    selectedUsers.value = []
    userStore.clearSelection()
    
    // 刷新用户列表
    await loadUsers(currentSearchParams.value)
  } catch (error) {
    // 处理错误情况
    if (error.message) {
      showError(error.message)
    } else {
      showError('角色分配失败')
    }
    console.error('Role assignment error:', error)
  } finally {
    loading.value = false
  }
}

// 处理用户新增/编辑确认
const handleUserFormConfirm = async (formData) => {
  try {
    if (formData.id) {
      // 编辑模式 - 使用PATCH更新部分字段
      const updateData = {
        username: formData.username,
        real_name: formData.real_name,
        email: formData.email,
        phone: formData.phone,
        status: formData.status
      }
      
      // 如果提供了角色，添加到更新数据中
      if (formData.roles && formData.roles.length > 0) {
        updateData.roles = formData.roles
      }
      
      await userService.updateUserPartial(formData.id, updateData)
      showSuccess('更新成功')
    } else {
      // 新增模式
      await userService.addUser(formData)
      showSuccess('添加成功')
    }
    // 刷新用户列表
    await loadUsers(currentSearchParams.value)
    // 清空选择状态
    selectedUsers.value = []
    userStore.clearSelection()
  } catch (error) {
    if (error.message === '该用户名已被使用') {
      showError('添加失败：该用户名已被使用')
    } else if (error.response?.data?.message) {
      showError(`操作失败：${error.response.data.message}`)
    } else {
      showError(formData.id ? '更新失败' : '添加失败')
    }
    console.error('User form error:', error)
  }
}

// 监听角色分配对话框取消
const handleAssignCancel = () => {
  const selection = userStore.cancelSelection()
  dataTableRef.value?.setSelection(selection)
}

// 对话框关闭时清理当前编辑的用户
const handleDialogClose = () => {
  userStore.clearCurrentUser()
}

// 监听分页变化
watch(
  () => [pagination.value.currentPage, pagination.value.pageSize],
  () => loadUsers(currentSearchParams.value)
)

// 处理从详情对话框启动编辑
const handleDetailEdit = () => {
  // 由于userStore.currentUser已在UserDetailDialog中设置
  // 这里只需打开表单对话框，表单会自动从store中获取数据
  nextTick(() => {
    userFormDialogRef.value?.openDialog()
  })
}

onMounted(() => {
  loadUsers()
})
</script>

<template>
  <div class="user-list">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <div class="batch-actions-left" v-if="selectedUsers.length">
            <el-button type="primary" @click="handleBatchAction('assign')">
              角色分配
            </el-button>
            <el-button type="success" @click="handleBatchAction('enable')">
              批量启用
            </el-button>
            <el-button type="warning" @click="handleBatchAction('disable')">
              批量禁用
            </el-button>
            <el-button type="danger" @click="handleBatchAction('delete')">
              批量删除
            </el-button>
          </div>
          <span v-else>用户管理</span>
          
          <div class="header-actions">
            <el-dropdown split-button type="primary" @click="handleBatchAction('add')" @command="handleBatchAction">
              添加用户
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="export">导出数据</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </template>
      
      <!-- 常规搜索 -->
      <div v-if="!showAdvancedSearch" class="search-container">
        <search-bar @search="handleSearch" />
        <div class="advanced-toggle">
          <el-button type="primary" link @click="toggleAdvancedSearch">
            高级搜索
            <el-icon class="el-icon--right"><ArrowDown /></el-icon>
          </el-button>
        </div>
      </div>
      
      <!-- 高级搜索 -->
      <advanced-search-form 
        v-if="showAdvancedSearch"
        @search="handleAdvancedSearch"
        @cancel="cancelAdvancedSearch"
      />
      
      <data-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        :columns="columns"
        v-model:pagination="pagination"
        @action="handleTableAction"
        @selection-change="handleSelectionChange"
        :selection-disabled="isAdminUser"
      >
        <template #roles="{ row }">
          <div class="flex gap-2 flex-wrap">
            <template v-if="row.roles && row.roles.length > 0">
              <el-tag 
                v-for="(role, index) in row.roles" 
                :key="index"
                :type="getRoleType(role.code)"
                size="small"
              >
                {{ role.name }}
              </el-tag>
            </template>
            <template v-else>
              <span class="text-gray-400">无角色</span>
            </template>
          </div>
        </template>
        
        <template #status="{ row }">
          <el-tag 
            :type="row.status === 1 ? 'success' : 'danger'"
            size="small"
          >
            {{ row.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </template>
        
        <template #actions="{ row }">
          <el-button link type="primary" @click="handleTableAction({ action: 'detail', row })">
            查看
          </el-button>
          <el-button 
            link 
            type="primary" 
            @click="handleTableAction({ action: 'edit', row })"
            :disabled="isAdminUser(row)"
            :class="{ 'admin-disabled': isAdminUser(row) }"
          >
            编辑
          </el-button>
          <el-button 
            link 
            type="primary" 
            @click="handleTableAction({ action: 'assign', row })"
            :disabled="isAdminUser(row)"
            :class="{ 'admin-disabled': isAdminUser(row) }"
          >
            分配角色
          </el-button>
          <el-button 
            link 
            :type="row.status === 1 ? 'warning' : 'success'" 
            @click="handleTableAction({ action: 'status', row })"
            :disabled="isAdminUser(row)"
            :class="{ 'admin-disabled': isAdminUser(row) }"
          >
            {{ row.status === 1 ? '禁用' : '启用' }}
          </el-button>
          <el-button 
            link 
            type="danger" 
            @click="handleTableAction({ action: 'delete', row })"
            :disabled="isAdminUser(row)"
            :class="{ 'admin-disabled': isAdminUser(row) }"
          >
            删除
          </el-button>
        </template>
      </data-table>
    </el-card>
    
    <role-assign-dialog
      ref="roleAssignDialogRef"
      :selected-users="selectedUsers"
      @confirm="handleRoleAssignConfirm"
      @cancel="handleAssignCancel"
    />
    
    <user-form-dialog
      ref="userFormDialogRef"
      :edit-mode="Boolean(userStore.currentUser)"
      :edit-data="userStore.currentUser"
      @confirm="handleUserFormConfirm"
      @closed="handleDialogClose"
    />
    
    <user-detail-dialog
      ref="userDetailDialogRef"
      @edit="handleDetailEdit"
    />
  </div>
</template>

<style scoped>
.user-list {
  height: 100%;
}

.page-card {
  margin: 0px;
  background-color: var(--el-bg-color);
  border-color: var(--el-border-color-lighter);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.batch-actions-left {
  display: flex;
  gap: 8px;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.search-container {
  position: relative;
}

.advanced-toggle {
  position: absolute;
  top: 10px;
  right: 10px;
}

:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.el-dropdown-menu) {
  background-color: var(--el-bg-color);
  border-color: var(--el-border-color-lighter);
}

:deep(.el-dropdown-menu__item:not(.is-disabled):hover) {
  background-color: var(--el-fill-color-light);
}

:deep(.el-card__header) {
  border-bottom-color: var(--el-border-color-lighter);
}

.flex {
  display: flex;
}

.flex-wrap {
  flex-wrap: wrap;
}

.gap-2 {
  gap: 0.5rem;
}

.text-gray-400 {
  color: #9ca3af;
}

.admin-disabled {
  color: var(--el-text-color-disabled);
  cursor: not-allowed;
}
</style> 